package app

import (
	"github.com/APP/internal/app/system/dict"
	"github.com/APP/internal/app/system/permission"
	role "github.com/APP/internal/app/system/roles"
	"github.com/APP/internal/app/system/route"
	"github.com/APP/internal/app/system/user"
	"github.com/APP/internal/handler"
	"github.com/APP/internal/middleware"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"time"
)

// Routers 初始化总路由
func Routers(a gin.HandlerFunc) *gin.Engine {
	// 创建Gin引擎
	r := gin.New()

	// 设置为发布模式，禁用调试输出
	gin.SetMode(gin.ReleaseMode)

	// 添加zap日志中间件
	r.Use(a)

	// 添加恢复中间件
	r.Use(gin.Recovery())

	// 配置CORS
	config := cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization", "x-token", "token"},
		ExposeHeaders:    []string{"new-token", "new-expires-at"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}
	r.Use(cors.New(config))

	// 健康检查接口
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "测试通过咯",
		})
	})

	// 初始化处理器
	//authHandler := handler.NewAuthHandler()

	// 公开路由组
	publicGroup := r.Group("/api/v1")
	{
		// 认证相关路由
		auth := publicGroup.Group("/auth")
		{
			auth.POST("/login", handler.NewAuthHandler().Login)
			auth.POST("/register", handler.NewAuthHandler().Register)
		}
	}

	// 需要认证的路由组
	privateGroup := r.Group("/api/v1")
	privateGroup.Use(middleware.JWTAuth())
	{
		user.RegisterUserRoutes(privateGroup) //注册用户路由
		dict.RegisterDictRoutes(privateGroup) //注册字典路由
		permission.RegisterPermissionRoutes(privateGroup)
		route.RegisterRouteRoutes(privateGroup)
		role.RegisterRoleRoutes(privateGroup)
	}

	return r
}
